package vn.edu.ptithcm.pim.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.StringMultipartFileEditor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import vn.edu.ptithcm.pim.constant.Constants;
import vn.edu.ptithcm.pim.constant.UrlConstants;
import vn.edu.ptithcm.pim.dom.News;
import vn.edu.ptithcm.pim.dom.User;
import vn.edu.ptithcm.pim.service.NewsService;
import vn.edu.ptithcm.pim.service.UserService;
import vn.edu.ptithcm.pim.util.FileUtil;
import vn.edu.ptithcm.pim.util.ParamUtil;

@SuppressWarnings("deprecation")
public class HandleNewsController extends SimpleFormController {

	private NewsService newsService;
	private UserService userService;

	Logger log = Logger.getLogger(HandleNewsController.class);

	public HandleNewsController() {
		super();
		setSessionForm(true);
		setCommandName("news");
		setCommandClass(News.class);
		setFormView(UrlConstants.HANDLE_NEWS_URL);
		setSuccessView(UrlConstants.HANDLE_NEWS_URL);
	}

	@Override
	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		News news = null;
		int id = ParamUtil.getInteger(request, "id", 0);
		news = newsService.findById(new Long(id));
		if (news == null) {
			news = new News();
		}
		return news;
	}

	@Override
	public void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		if (request instanceof MultipartHttpServletRequest) {
			binder.registerCustomEditor(String.class,
					new StringMultipartFileEditor());
		}
	}

	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		log.info("HandleNewsController||onSubmit");
		String loginName = userService.getCurrentLogin(request);
		User user = userService.findByLoginName(loginName);
		if (user != null) {
			String visa = user.getEmployee().getVisa();
			News informNews = (News) command;
			String cmd = ParamUtil.getString(request, Constants.CMD, "");
			String imageurl = FileUtil.transferTo(request, "imageurl",
					Constants.UPLOADED_FILE_FOLDER);
			if (!imageurl.isEmpty()) {
				informNews.setImageurl(imageurl);
			} else if (Constants.EDIT.equals(cmd)) {
				long id = informNews.getNewsid();
				News inDBNews = newsService.findById(id);
				if (inDBNews != null) {
					informNews.setImageurl(inDBNews.getImageurl());
				}
			}
			Date now = new Date();
			if (Constants.EDIT.equals(cmd)) {
				informNews.setUpdatedAt(now);
				informNews.setUpdatedBy(visa);
				newsService.saveOrUpdate(informNews);
				request.setAttribute("editOK", true);
				log.debug("edited");

			} else if (Constants.ADD.equals(cmd)) {
				informNews.setCreatedAt(now);
				informNews.setCreatedBy(visa);
				informNews.setUpdatedAt(now);
				informNews.setUpdatedBy(visa);
				newsService.save(informNews);
				request.setAttribute("addOK", true);
				log.debug("added");
			}
		}

		return showForm(request, response, errors);
	}

	@Override
	protected ModelAndView showForm(HttpServletRequest request,
			HttpServletResponse response, BindException errors)
			throws Exception {
		if (userService.isSignedIn(request)) {
			Map<String, Object> bean = new HashMap<String, Object>();
			String loginName = userService.getCurrentLogin(request);
			bean.put("user", userService.findByLoginName(loginName));
			bean.put("isSigned", true);
			bean.put("isAdmin", userService.isAdmin(loginName));
			bean.put(Constants.LOGIN_NAME, loginName);
			bean.put(Constants.USER_NAME, userService.getUsername(loginName));

			String cmd = ParamUtil.getString(request, Constants.CMD, "");
			bean.put(Constants.CMD, cmd);

			String returnToFullPageURL = ParamUtil.getString(request,
					Constants.RETURN_TO_FULL_PAGE_URL, "");

			if (returnToFullPageURL.isEmpty()) {
				returnToFullPageURL = request.getHeader("referer");
			}
			bean.put(Constants.RETURN_TO_FULL_PAGE_URL, returnToFullPageURL);

			request.setAttribute("bean", bean);
		} else {
			String cmd = ParamUtil.getString(request, Constants.CMD, "");
			String redirectLink = "";
			if (Constants.ADD.equals(cmd)) {
				redirectLink = UrlConstants.HANDLE_NEWS_URL + UrlConstants.HTM;
			} else if (Constants.EDIT.equals(cmd)) {
				int id = ParamUtil.getInteger(request, "id", 0);
				redirectLink = UrlConstants.HANDLE_NEWS_URL + UrlConstants.HTM
						+ "?id=" + id;
			}
			log.info("HandleNewsController || redirectLink : " + redirectLink);
			request.getSession().setAttribute("redirectLink", redirectLink);
			response.sendRedirect(UrlConstants.HOME_PAGE_URL + UrlConstants.HTM);
		}
		return super.showForm(request, response, errors);
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public NewsService getNewsService() {
		return newsService;
	}

	public void setNewsService(NewsService newsService) {
		this.newsService = newsService;
	}

	public UserService getUserService() {
		return userService;
	}

}
